package com.ip.getip.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ Description   :  aria2远程调用http
 * @ Author        :  leixin
 * @ CreateDate    :  2020/5/8-14:07
 * @ Version       :  1.0
 */
@Service
public class Aria2RPC {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${aria2.downs}")
    private int number;
    @Value("${aria2.path}")
    private String path;
    @Value("${aria2.addr}")
    private String addr;

    public String aria2(String url,String name) {
        //查看当前任务数据
        Boolean downs = maxDowns(number);
        if (!downs) {
            return "超过最大下载任务数量";
        }
        return Downs(url,name);
    }

    /**
     * 当前地址加入进aria2
     *
     * @param url
     * @param name
     * @return
     */
    public String Downs(String url,String name) {
        String token = "token:leixin991426";
        Map map = new HashMap();
        map.put("jsonrpc", "2.0");
        map.put("id", "QXJpYU5nXzE1NDgzODg5MzhfMC4xMTYyODI2OTExMzMxMzczOA==");
        map.put("method", "aria2.addUri");
        Map listMap = new HashMap();
        listMap.put("out", name);
        listMap.put("dir", path);
        List pam = new ArrayList();
        List list = new ArrayList<>();
        list.add(url);
        pam.add(token);
        pam.add(list);
        pam.add(listMap);
        map.put("params", pam);
        String s = JSON.toJSONString(map);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(addr, s, String.class);
        return forEntity.getStatusCode().toString();
    }

    /**
     * 验证aria2任务数是否可以添加
     *
     * @param number
     * @return
     */
    public Boolean maxDowns(int number) {
        List list = new ArrayList();
        list.add("token:leixin991426");
        Map map = new HashMap();
        map.put("jsonrpc", "2.0");
        map.put("id", "QXJpYU5nXzE1NDgzODg5MzhfMC4xMTYyODI2OTExMzMxMzczOA==");
        map.put("method", "aria2.tellActive");
        map.put("params", list);
        String s = JSON.toJSONString(map);
        ResponseEntity<String> forEntity = new RestTemplate().postForEntity(addr, s, String.class);
        Map parseObject = JSON.parseObject(forEntity.getBody(), Map.class);
        if (parseObject.get("result") != null) {
            JSONArray result = JSON.parseArray(parseObject.get("result").toString());
            if (result.size() < number) {
                return true;
            }
            return false;
        }
        return false;
    }
}
